// pages/Order/SubmitVehicleOrder/SubmitVehicleOrder.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryTravelVehicleStoreDetails , queryTravelVehicleSafeConfig , submitTravelVehicleRentalOrderForm } from '../../../api/vehicle';
import { queryTravelUser , payTravelOrderForm } from '../../../api/travel';
import { checkUserPasswordIsSet } from '../../../api/login';
import { getUserAccount , queryUserWechatOpenId } from '../../../api/user';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    item: {},
    store: {},
    province: '',
    city: '',
    country: '',
    town: '',
    detailedAddress: '',
    rentCarStartCurrent: '',
    rentCarStartYear: '',
    rentCarEndYear: '',
    rentCarStartDate: '', // 开始时间的日期
    rentCarStartWeek: '', // 开始时间的星期
    rentCarStartTime: '', // 开始租车时间
    rentCarDateDiff: '', // 租还间隔时间
    rentCarEndCurrent: '',
    rentCarEndDate: '', // 还车时间的日期
    rentCarEndWeek: '', // 还车时间的星期
    rentCarEndTime: '', // 还车时间
    infoCont: [], // 基本信息
    configCont: [], // 配置信息
    price: 0, // 租车总价
    priceConfig: {},
    showScheduleFee: false,
    selTravelUserList: [], // 所选出行人列表
    selTravelUserListId: '1', // 复选框所选出行人列表ID
    travelUserPop: false,
    number: 1,
    safeguardConfigIds: [], // 租车商家保障ID
    safeguardConfig: [],
    payType: [2],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.item){
      var item = JSON.parse(options.item);
      var store = JSON.parse(options.store);
      console.log(item,'item')
      console.log(store,'store')
      this.setData({
        item: item,
        store: store,
        province: options.province,
        city: options.city,
        country: options.country,
        town: options.town,
        detailedAddress: options.detailedAddress,
        rentCarStartDate: wx.getStorageSync('rentCarStartDate'),
        rentCarStartTime: wx.getStorageSync('rentCarStartTime'),
        rentCarStartWeek: wx.getStorageSync('rentCarStartWeek'),
        rentCarEndDate: wx.getStorageSync('rentCarEndDate'),
        rentCarEndTime: wx.getStorageSync('rentCarEndTime'),
        rentCarDateDiff: wx.getStorageSync('rentCarDateDiff'),
        rentCarEndWeek: wx.getStorageSync('rentCarEndWeek'),
        rentCarStartCurrent: wx.getStorageSync('rentCarStartCurrent'),
        rentCarEndCurrent: wx.getStorageSync('rentCarEndCurrent'),
        rentCarStartYear: wx.getStorageSync('rentCarStartYear'),
        rentCarEndYear: wx.getStorageSync('rentCarEndYear'),
      })
      this._queryTravelVehicleSafeConfig();
      this._queryTravelUser({init: true});
      this._queryUserWechatUnionId();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this._getUserAccount('0');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 获取租车门店商家保障
  _queryTravelVehicleSafeConfig(){
    let _this = this;
    queryTravelVehicleSafeConfig({vehicleId: _this.data.item.id,storeId: _this.data.store.id,})
    .then(res => {
      if(res.success){
        let arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          if(element.safeguardName.indexOf('服务') != -1 && element.isDefault != '1'){
            element.isMore = '0'
          }else{
            element.isMore = '1'
          }
          console.log(element.safeguardContent,'safeguardContent')
          let safeguardContentList = element.safeguardContent ? element.safeguardContent.replace(/\n/g,'#$%^&*()!@#').split('#$%^&*()!@#') : [];
          let list = [];
          for (let j = 0; j < safeguardContentList.length; j++) {
            const cont = safeguardContentList[j];
            let obj = {};
            if(cont.substring(0,5).indexOf('无需') != -1){
              obj.type = '1';
            }
            obj.cont = cont;
            list.push(obj);
          }
          element.safeguardContentList = list;
          arr.push(element);
        }
        _this.setData({
          safeguardConfig: arr,
        })
        _this._queryTravelVehicleStoreDetails({});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择租车保障
  selSafeId(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let safeguardConfigIds = this.data.safeguardConfigIds;
    let safeguardConfigList = this.data.safeguardConfig;
    if(item.isDefault == '1'){
      this._queryTravelVehicleStoreDetails({safeguardConfigIds: safeguardConfigIds.join(',')})
      return;
    }
    if(item.isMore == '1'){
      if(safeguardConfigIds.indexOf(item.id) != -1){
        safeguardConfigIds.splice(safeguardConfigIds.indexOf(item.id),1)
      }else{
        safeguardConfigIds.push(item.id)
      }
    }else{
      if(safeguardConfigIds.indexOf(item.id) != -1){
        safeguardConfigIds.splice(safeguardConfigIds.indexOf(item.id),1)
      }else{
        let arr = [];
        for (let index = 0; index < safeguardConfigList.length; index++) {
          const element = safeguardConfigList[index];
          for (let j = 0; j < safeguardConfigIds.length; j++) {
            const itm = safeguardConfigIds[j];
            if(itm == element.id){
              if(element.isMore == '1'){
                arr.push(itm)
              }
            }
          }
        }
        safeguardConfigIds = arr;
        safeguardConfigIds.push(item.id)
      }
    }
    console.log(safeguardConfigIds,'safeguardConfigIds')
    this.setData({safeguardConfigIds})
    this._queryTravelVehicleStoreDetails({safeguardConfigIds: safeguardConfigIds.join(',')})
  },
  // 获取租车门店详情
  _queryTravelVehicleStoreDetails({safeguardConfigIds}){
    let _this = this;
    queryTravelVehicleStoreDetails({storeConfigId: _this.data.store.config.id,safeguardConfigIds: safeguardConfigIds,startTime: _this.data.rentCarStartYear + '-' + _this.data.rentCarStartDate + ' ' + _this.data.rentCarStartTime,endTime: _this.data.rentCarEndYear + '-' + _this.data.rentCarEndDate + ' ' + _this.data.rentCarEndTime})
    .then(res => {
      if(res.success){
        _this.setData({
          priceConfig: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 费用明细
  changeShow(){
    this.setData({
      showScheduleFee: !this.data.showScheduleFee,
    })
  },
  // 查询出行人
  _queryTravelUser({init}){
    let _this = this;
    queryTravelUser({page: 0,size: 99})
    .then(res => {
      if(res.success){
        _this.setData({
          travelUserList: res.data.content,
        })
        if(init){
          _this.setData({
            selTravelUserList: _this.data.travelUserList.length > 0 ? [_this.data.travelUserList[0]] : [],
            selTravelUserListId: _this.data.travelUserList.length > 0 ? _this.data.travelUserList[0].id : ''
          })
        }
        _this.setData({
          selTravelUserListId: _this.data.selTravelUserListId,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 更多出行人
  showTravelUserList(){
    var id = '';
    for (let index = 0; index < this.data.selTravelUserList.length; index++) {
      const item = this.data.selTravelUserList[index];
      // list.push(item.id );
      id = item.id;
    }
    this.setData({
      travelUserPop: true,
      selTravelUserListId: id,
    })
  },
  onTravelUserPopClose(){
    this.setData({
      travelUserPop: false,
    })
  },
  // 添加出行人
  addTravelUser(){
    let _this = this;
    wx.navigateTo({
      url: `/pages/Users/AddTravelUser/AddTravelUser`,
      events: {
        'updateTravelUser': function(data){
          _this._queryTravelUser({});
        }
      }
    })
  },
  // 删除选择出行人
  delSelTravelPop(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    var index = this.data.selTravelUserList.findIndex(itm => itm.id == item.id);
    var list = this.data.selTravelUserList;
    list.splice(index,1);
    this.setData({
      selTravelUserList: list,
    })
  },
  // 修改联系人信息
  updateTravelUser(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/Users/AddTravelUser/AddTravelUser?id=${item.id}`,
      events: {
        'updateTravelUser': function(data){
          _this._queryTravelUser({init: true});
        }
      }
    })
  },
  // 选择出行人
  onSelTravelPeoChange(e){
    console.log(e,'e.detail')
    var orderSum = this.data.number;
    console.log(orderSum);
    if(e.detail.length > orderSum){
      wx.showToast({
        title: `最大游玩人数为${orderSum}`,
        icon: 'none',
      });
      return;
    }
    this.setData({
      selTravelUserListId: e.detail,
    })
  },
  // 确认选择出行人
  submitSelTravelUser(){
    let _this = this;
    console.log(_this.data.selTravelUserListId,'selId')
    const selTravelUserListId = _this.data.selTravelUserListId;
    const travelUserList = _this.data.travelUserList;
    let list = [];
    for (let index = 0; index < travelUserList.length; index++) {
      const item = travelUserList[index];
      // for (let j = 0; j < selTravelUserListId.length; j++) {
      //   const itm = selTravelUserListId[j];
      //   if(itm == item.id){
      //     list.push(item);
      //   }
      // }
      if(selTravelUserListId == item.id){
        list.push(item);
      }
    }
    _this.setData({
      selTravelUserList: list,
      travelUserPop: false,
    })
  },
  // 下单
  submitOrder(){
    let _this = this;
    const { selTravelUserList , number } = _this.data;
    if(selTravelUserList.length < number){
      wx.showToast({
        title: `请补充承租人信息`,
        icon: 'none',
      });
      return;
    }
    this.setData({orderPayPop: true})
    // this._submitOrder();
  },
  // 下单
  _submitOrder(){
    let _this = this;
    const { province ,city ,country , town , detailedAddress , store , safeguardConfigIds , rentCarStartYear , rentCarStartDate , rentCarStartTime , rentCarEndYear , rentCarEndDate , rentCarEndTime , selTravelUserList } = _this.data;
    submitTravelVehicleRentalOrderForm({storeConfigId: store.config.id,safeguardConfigIds: safeguardConfigIds.join(','),startTime: rentCarStartYear + '-' + rentCarStartDate + ' ' + rentCarStartTime,endTime: rentCarEndYear + '-' + rentCarEndDate + ' ' + rentCarEndTime,pickUpLocation: province != '' ? province + city + country + town + detailedAddress : store.province+store.city+store.area+store.town+store.detailedAddress,giveBackLocation: province != '' ? province + city + country + town + detailedAddress : store.province+store.city+store.area+store.town+store.detailedAddress,driverName: selTravelUserList[0].name,driverPhone: selTravelUserList[0].phone,driverIdCard: selTravelUserList[0].idCard})
      .then(res => {
        if(res.success){
          _this.pay({orderCode:res.data.data.orderCode,payType:_this.data.payType.indexOf(0) != -1 ? '0' : _this.data.payType[0],amount: _this.data.payType.length > 1 ? _this.data.balance > _this.data.price ? _this.data.price : _this.data.balance : ''})
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  pay({orderCode,payType,amount}){
    let _this = this;
    payTravelOrderForm({isAllPay: '1',payType: payType,orderCode: orderCode,openId: _this.data.unionid,payAmount: amount,payPassword: payType == '0' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({orderCode: orderCode,payType: payType,wechatSign: res.data ? res.data.data : res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({orderCode,payType,wechatSign}){
    let _this = this;
    if(_this.data.payType.indexOf(0) != -1 && payType == 0){
      // if(_this.data.payType.length == 1 || _this.data.balance > _this.data.price || _this.data.balance == _this.data.price){
      //   wx.navigateTo({
      //     url: '/pages/Order/PaySuccess/PaySuccess',
      //   })
      // }else{
      //   // 组合支付
      //   var arr = JSON.parse(JSON.stringify(_this.data.payType));
      //   arr.splice(arr.indexOf(1),1);
      //   _this.pay({orderCode: orderCode,payType: arr[0],amount: _this.data.price - _this.data.balance})
      // }
      wx.navigateTo({
        url: '/pages/Order/PaySuccess/PaySuccess',
      })
    }else{
      // console.log(JSON.parse(wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          wx.navigateTo({
            url: '/pages/Order/PaySuccess/PaySuccess',
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 关闭支付方式选择
  orderPayPopClose(){
    this.setData({
      orderPayPop: false,
    })
  },
  // 确认支付
  submitPayOrder(){},
  // 校验是否设置过支付密码
  _checkUserPasswordIsSet(){
    let _this = this;
    return new Promise((resolve,reject) => {
      checkUserPasswordIsSet({})
      .then(res => {
        if(res.success){
          resolve(true)
        }else{
          resolve(false)
        }
      })
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              unionid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(type){
    let _this = this;
    getUserAccount(type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            balance : res.data.balance,
            payType: res.data.balance > 0 ? [0] : []
          })
        }else if(type == 5){
          _this.setData({
            integral : res.data.balance,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 是否选择余额支付
  selBalancePay(){
    if(this.data.balance == 0){
      return;
    }
    var arr = this.data.payType;
    console.log(arr,'arr')
    console.log(arr.indexOf(1))
    // if(arr.indexOf(1) != -1){
    //   arr.splice(arr.indexOf(1),1)
    //   console.log(arr,'arr')
    //   this.setData({
    //     payType: arr,
    //   })
    // }else{
    //   arr.push(1);
    //   this.setData({
    //     payType: arr,
    //   })
    // }
    this.setData({
      payType: ['0']
    })
  },
  // 切换支付渠道
  selPayType(e){
    console.log(e);
    let payType = e.target.dataset.type||e.currentTarget.dataset.type;
    var arr = this.data.payType;
    console.log(arr,'arr')
    console.log(arr.indexOf(payType))
    // if(arr.indexOf(payType) != -1){
    //   arr.splice(arr.indexOf(payType),1)
    //   console.log(arr,'arr')
    //   this.setData({
    //     payType: arr,
    //   })
    // }else{
    //   arr.push(payType);
    //   this.setData({
    //     payType: arr,
    //   })
    // }
    this.setData({
      payType: [2]
    })
  },
  // 确认选择支付渠道
  async submitPayOrder(){
    let _this = this;
    if(_this.data.payType.indexOf(0) != -1){
      if(_this.data.payType.length == 1 && _this.data.price > _this.data.balance){
        wx.showToast({
          title: '当前余额不足，请更换其他支付方式，或者组合支付',
          icon: 'none'
        })
        return;
      }
      const isSetPayPassword = await _this._checkUserPasswordIsSet();
      if(!isSetPayPassword){
        var phone = wx.getStorageSync('phone');
        if(phone.length != 11){
          wx.showModal({
            title: '温馨提示',
            content: '当前暂未设置交易密码，设置交易密码之前需要绑定手机号，是否前往绑定？',
            success: (modal) =>{
              if(modal.confirm){
                wx.navigateTo({
                  url: '/pages/Users/BindPhone/BindPhone',
                })
              }
            },
          })
          return;
        }
        wx.showModal({
          title: '温馨提示',
          content: '暂未设置交易密码，是否前往设置？',
          success: (modal) =>{
            if(modal.confirm){
              wx.navigateTo({
                url: '/pages/Users/UpdatePayPassword/UpdatePayPassword',
              })
            }
          },
        })
        return;
      }
      const child = _this.selectComponent('.pay-passwordAuth');
      console.log(child,'child')
      child.clearPassword();
      child.openPayAuth();
    }else{
      _this._submitOrder();
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    console.log(e,'e')
    this.setData({
      payPassword: e.detail,
    })
    this._submitOrder();
  },
})